"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
from dao.build_dao import BuildDao
from do.build_do import BuildDo
from service.plan_service import PlanService
from service.testcase_service import TestcaseService

from utils.jenkins_utils import JenkinsUtils

build_dao = BuildDao()
testcase_service = TestcaseService()
plan_service = PlanService()


class BuildService:

    def get(self, build_id):
        # 通过id查询数据
        return build_dao.get(build_id)

    def list(self):
        # 返回所有
        return build_dao.list()

    def save(self, plan_id):
        # 保存构建任务
        plan_detail = plan_service.get(plan_id)
        if plan_detail:
            method_list = [testcase.method for testcase in plan_detail.testcases]
            methods = " ".join(method_list)
            # 执行测试用例
            report = JenkinsUtils.invoke(methods)
            # 保存构建
            build_do = BuildDo(plan_id=plan_id, report=report)
            return build_dao.save(build_do)
        else:
            return False

    def delete(self, build_id):
        # 存在则进行删除，否则返回错误
        build = self.get(build_id)
        if not build:
            return False
        else:
            return build_dao.delete(build_id)
